package com.live.activity;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Calendar;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputFilter;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.live.common.Constant;
import com.live.common.LiveCommon;
import com.live.common.LiveImageHelper;
import com.live.task.LiveUser;
import com.live.tools.LiveTools;

public class LiveUserSettingActivity extends LiveBaseActivity {
	private TextView man = null;
	private TextView woman = null;
	private String userSex = Constant.USER_SEX_MAN;
	private String userBirthday;
	private String userSign;
	private String userMail;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.user_setting);

		// 设置头部信息
		LiveCommon.setHead(LiveUserSettingActivity.this, (LinearLayout) findViewById(R.id.liveHead),
				R.string.user_setting, R.string.user_save_btn);

		// 头部按钮设置（保存）
		Button saveBtn = (Button) findViewById(R.id.headFuncBtn);
		saveBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {

				// 取得用户ID
				TextView userId = (TextView) findViewById(R.id.userId);

				// 取得用户密码
				EditText userPwd = (EditText) findViewById(R.id.userPwd);
				EditText userPwdRp = (EditText) findViewById(R.id.userPwdRp);

				// 用户密码校验
				if (!userPwd.getText().toString().equals(userPwdRp.getText().toString())) {
					Toast.makeText(v.getContext(), Constant.PWD_DIFF, Toast.LENGTH_LONG).show();
					return;
				}

				// 取得用户生日
				TextView birthday = (TextView) findViewById(R.id.userBirthday);
				userBirthday = (String) birthday.getText();

				// 取得用户签名
				EditText sign = (EditText) findViewById(R.id.userSign);
				userSign = sign.getText().toString();

				// 取得用户邮箱
				EditText mail = (EditText) findViewById(R.id.userMail);
				userMail = mail.getText().toString();

				String url = Constant.SITE_URL + "live_user.php?locale=" + LiveTools.getLocaleLanguage()
						+ "&userDeviceId=" + deviceID;
				url += "&id=" + store.getString("id", null) + "&userId=" + userId.getText().toString() + "&userPwd="
						+ userPwd.getText().toString() + "&userSex=" + userSex + "&userBirthday=" + userBirthday
						+ "&userSign=" + userSign + "&userMail=" + userMail + "&type=e";

				user.setId(store.getString("id", null));
				user.setUserId(userId.getText().toString());
				user.setUserPwd(userPwd.getText().toString());
				user.setUserBirthday(userBirthday);
				user.setUserSign(userSign);
				user.setUserMail(userMail);
				user.setUserSex(userSex);
				user.setUserType("1");

				LiveUser task = new LiveUser(context, url, "编辑");
				task.execute(user);
			}
		});

		store = getSharedPreferences(Constant.PREFS_NAME, 0);

		// 设置帐号
		TextView userId = (TextView) findViewById(R.id.userId);
		userId.setText(store.getString("userId", null));

		// 设置头像
		ImageView userPic = (ImageView) findViewById(R.id.userPic);

		if (Constant.Y.equals(store.getString("userPic", null))) {
			LiveImageHelper.loadBitMap(userPic, store.getString("id", null), Constant.NUM_ZERO);
		}
		userPic.setOnClickListener(new ImageView.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				/* 开启Pictures画面Type设定为image */
				intent.setType("image/*");
				/* 使用Intent.ACTION_GET_CONTENT这个Action */
				intent.setAction(Intent.ACTION_GET_CONTENT);
				/* 取得相片后返回本画面 */
				startActivityForResult(intent, 1);
			}
		});

		// 设置性别
		man = (TextView) findViewById(R.id.man);
		man.setOnClickListener(new TextView.OnClickListener() {
			@Override
			public void onClick(View v) {
				userSex = Constant.USER_SEX_MAN;
				man.setBackgroundDrawable(getResources().getDrawable(R.drawable.man_on));
				woman.setBackgroundDrawable(getResources().getDrawable(R.drawable.woman_off));
			}
		});

		woman = (TextView) findViewById(R.id.woman);
		woman.setOnClickListener(new TextView.OnClickListener() {
			@Override
			public void onClick(View v) {
				userSex = Constant.USER_SEX_WOMAN;
				man.setBackgroundDrawable(getResources().getDrawable(R.drawable.man_off));
				woman.setBackgroundDrawable(getResources().getDrawable(R.drawable.woman_on));
			}
		});
		if (Constant.USER_SEX_WOMAN.equals(store.getString("userSex", null))) {
			man.setBackgroundDrawable(getResources().getDrawable(R.drawable.man_off));
			woman.setBackgroundDrawable(getResources().getDrawable(R.drawable.woman_on));
		}

		// 设置生日
		if (store.getString("userBirthday", null) != null) {
			TextView birthday = (TextView) findViewById(R.id.userBirthday);
			birthday.setText(store.getString("userBirthday", null));
		}

		// 设置签名
		if (store.getString("userSign", null) != null && !"null".equals(store.getString("userSign", null))) {
			EditText userSign = (EditText) findViewById(R.id.userSign);
			userSign.setText(store.getString("userSign", null));
			userSign.setFilters(new InputFilter[] { new InputFilter.LengthFilter(30) });
		}

		// 设置邮箱
		if (store.getString("userMail", null) != null && !"null".equals(store.getString("userMail", null))) {
			EditText userMail = (EditText) findViewById(R.id.userMail);
			userMail.setText(store.getString("userMail", null));
		}

		// 单击日期
		ImageView calendar = (ImageView) findViewById(R.id.calendar);
		calendar.setOnClickListener(new ImageView.OnClickListener() {
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});

		// 清除缓存按钮
		Button clearBtn = (Button) findViewById(R.id.clearBtn);
		clearBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				LiveTools.deleteFile(context, "score_", null);
				Toast.makeText(v.getContext(), "缓存数据清除完毕！", Toast.LENGTH_LONG).show();
				finish();
			}
		});
	}

	// 设置要检索的日期
	private DatePickerDialog.OnDateSetListener mSetDateListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int month, int day) {
			Calendar cal = Calendar.getInstance();
			cal.set(year, month, day);
			String date = sdf.format(cal.getTime());

			TextView Birthday = (TextView) findViewById(R.id.userBirthday);
			Birthday.setText(date);

			userBirthday = date;
		}
	};

	protected Dialog onCreateDialog(int id) {
		Calendar c = Calendar.getInstance();
		switch (id) {
		case 0:
			return new DatePickerDialog(this, this.mSetDateListener, c.get(1), c.get(2), c.get(5));
		}
		return null;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			int maxWidth = 200;
			int maxHeight = 200;
			Uri uri = data.getData();
			try {
				Bitmap bitmap = LiveTools.uriToBitmap(uri, context);

				// 同比例压缩图片
				int originWidth = bitmap.getWidth();
				int originHeight = bitmap.getHeight();

				if (originWidth > maxWidth || originHeight > maxHeight) {

					int width = originWidth;
					int height = originHeight;

					// 若图片过宽, 则保持长宽比缩放图片
					if (originWidth > maxWidth) {
						width = maxWidth;
						double i = originWidth * 1.0 / maxWidth;
						height = (int) Math.floor(originHeight / i);
						bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);
					}

					// 若图片过长, 则从上端截取
					if (height > maxHeight) {
						height = maxHeight;
						bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
					}
				}

				// 保存临时文件
				LiveImageHelper.saveImage(bitmap, "tmp");
				ImageView imageView = (ImageView) findViewById(R.id.userPic);

				// 将Bitmap设定到ImageView
				imageView.setImageBitmap(bitmap);

				// 设定用户头像
				user.setUserPicBitmap(bitmap);
			} catch (FileNotFoundException e) {
				Log.e("Exception", e.getMessage(), e);
			} catch (IOException e) {
				Log.e("Exception", e.getMessage(), e);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}